import React, { useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
};
/**
 * 文件上传之前的验证
 * @param {*} file 
 * @returns 
 */
const beforeUpload = (file) => {
    console.log(file);
    //判断文件格式
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  //验证文件大小 file.size TB -- MB --- KB --byte
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const MyUpload = (props) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  const handleChange = (info) => {
    //正在上传中
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    //上传完成
    if (info.file.status === 'done') {
      // 本地选中了一张图片，将这张图片转化为base64编码字符串。保存setImageUrl
      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
      const res = info.file.response;
      props.setImgName(res.data)
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  return (
    <>
      <Upload
        name={props.name}
        listType="picture-card"
        className="avatar-uploader"
        action={props.action}
        beforeUpload={beforeUpload}
        onChange={handleChange}
      >
        {imageUrl || props.filePath ? (
          <img
            src={imageUrl || props.filePath}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
      
    </>
  );
};
export default MyUpload;